<template>
  <div class="app-container">
    <span style="font-size: medium;color: rgba(151,170,195) "> / 采购调拨 / 调拨计划 / 新增调拨</span>

    <el-row style="margin-top: 20px">
      <el-col :span="24" class="card-box">
        <el-card>
          <template #header><Monitor style="width: 1em; height: 1em; vertical-align: middle;" /> <span style="vertical-align: middle;">采购订单基本信息</span></template>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <table style="width: 100%;">
              <tbody>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">采购订单编号</div></td>
                <td class="el-table__cell is-leaf">
                  <div class="cell">{{planInfo.orderNo}}</div>
                </td>
                <td class="el-table__cell is-leaf"><div class="cell">调拨编号</div></td>
                <td class="el-table__cell is-leaf">
                  <div class="cell">{{planInfo.allocationNo}}</div>
                </td>
                <td class="el-table__cell is-leaf"><div class="cell">创建时间</div></td>
                <td class="el-table__cell is-leaf">
                  <div class="cell">{{planInfo.createdTime}}</div>
                </td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">*运送仓库</div></td>
                <td class="el-table__cell is-leaf">
                  <div class="cell">
                    <el-select style="width: 60%;" v-model="planInfo.warehouseNo">
                      <el-option
                          v-for="item in warehouses"
                          :key="item"
                          :label="item.label"
                          :value="item.value"
                      />
                    </el-select>
                  </div>
                </td>
                <td class="el-table__cell is-leaf"><div class="cell">*调拨时间</div></td>
                <td class="el-table__cell is-leaf">
                  <div class="cell">
                    <el-date-picker
                        v-model="planInfo.allocationDate"
                        type="date"
                        placeholder="请选择调拨时间"
                        format="YYYY/MM/DD"
                    />
                  </div>
                </td>
                <td class="el-table__cell is-leaf"><div class="cell">*预期到货时间</div></td>
                <td class="el-table__cell is-leaf">
                  <div class="cell">
                    <el-date-picker
                        v-model="planInfo.expectedDeliveryTime"
                        type="date"
                        placeholder="请选择预期到货时间"
                        format="YYYY/MM/DD"
                    />
                  </div>
                </td>
              </tr>
              <tr>
                <td class="el-table__cell is-leaf"><div class="cell">*发货地址</div></td>
                <td class="el-table__cell is-leaf">
                  <div class="cell">
                    <el-input
                        v-model="planInfo.origin"
                        placeholder="请输入发货地址"
                        clearable
                    />
                  </div>
                </td>
                <td class="el-table__cell is-leaf"><div class="cell">备注</div></td>
                <td class="el-table__cell is-leaf" colspan="3">
                  <div class="cell">
                    <el-input
                        v-model="planInfo.remarks"
                        placeholder="请输入备注"
                        type="textarea"
                        clearable
                    />
                  </div>
                </td>
              </tr>
              </tbody>
            </table>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24" class="card-box">
        <el-card>
          <template #header><Goods style="width: 1em; height: 1em; vertical-align: middle;" /> <span style="vertical-align: middle;">采购调拨信息</span></template>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <el-table v-loading="loading" :data="allocationDetails">
              <el-table-column label="采购调拨明细编号" align="center" prop="allocationDetailNo"/>
              <el-table-column label="货品批号" align="center" prop="rawProductBatch"/>
              <el-table-column label="货品名称" align="center" prop="rawProductName"/>
              <el-table-column label="待调拨重量(吨)" align="center" prop="remainWeight"/>
              <el-table-column label="调拨重量(吨)" align="center" prop="weight">
                <template #default="scope">
                  <el-input-number v-model="scope.row.weight"
                                   :precision="2" controls-position="right" style="width: 90%;" :max="scope.row.maxWeight"/>
                </template>
              </el-table-column>
              <el-table-column label="调拨件数(可空)" fixed="right" align="center" >
                <template #default="scope">
                  <el-input-number v-model="scope.row.transportQuantity"
                                   controls-position="right" style="width: 90%;"/>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>

      <el-col :span="24">
        <div style="display: flex; justify-content: right;
                margin-top: 30px; margin-right: 20px;gap: 10px">
          <el-button
              round
              icon="Back"
              class="custom-large-button"
              @click="handleBack"
          >返回</el-button>
          <el-button
              type="primary"
              round
              icon="Pointer"
              class="custom-large-button"
              @click="handleOrderGenerate"
          >提交</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>

import {getPurchaseOrder} from "@/api/purchase/purchaseOrder.js";
import {useRouter} from "vue-router";
import {getOrderDetail} from "@/api/purchase/orderDetail.js";
import {getRawProductDetailByOrderNo} from "@/api/purchase/RawProductDetail.js";
import {
  addAllocationPlan,
  getAllocationPlan,
  updateAllocationPlan
} from "@/api/purchase/AllocationPlan.js";
import {
  addAllocationDetailList,
  getAllocationDetail,
  getRawProductDetailByAllocationNo
} from "@/api/purchase/AllocationDetail.js";

const { proxy } = getCurrentInstance();
const router = useRouter();

const orderNo = ref("");
const allocationNo = ref("");
const orderInfo = ref({}); //订单信息
const orderDetails = ref([]);
const allocationDetails = ref([]);
const planInfo = ref({
  allocationNo:generateAllocationNumber(),
  orderNo: "",
  allocationDate: "",
  expectedDeliveryTime: "",
  weight: 0,
  weightUnit: "吨",
  transportQuantity: 0,
  warehouseNo: "",
  origin: "",
  destination: "",
  createdTime: getFormattedTime(),
  remarks: "",
}); //记录新增调拨计划信息

const loading = ref(false);
const activeName = ref("first");
const multipleTableRef = ref();

const warehouses = ref([
  {
    label:"仓库A",
    value:"Warehouse001",
    address:"河北省石家庄"
  },
  {
    label:"仓库B",
    value:"Warehouse002",
    address:"河北省石家庄"
  },
  {
    label:"仓库C",
    value:"Warehouse003",
    address:"河北省石家庄"
  },
  {
    label:"仓库D",
    value:"Warehouse004",
    address:"河北省石家庄"
  },
])

function initial(){
  if(proxy.$route.query.orderNo){
    orderNo.value = proxy.$route.query.orderNo;
    planInfo.value.orderNo = orderNo.value;
    getPurchaseOrder(orderNo.value).then(response => {
      orderInfo.value = response.data
      planInfo.value.origin = orderInfo.value.deliveryAddress;
    })
  }
  if(proxy.$route.query.allocationNo){
    allocationNo.value = proxy.$route.query.allocationNo;
    getAllocationPlan(allocationNo.value).then(response => {
      planInfo.value = response.data;
    })
    loading.value = true;
    getAllocationDetail(allocationNo.value).then(response => {
      allocationDetails.value = response.data;
      getOrderDetail(orderNo.value).then(response => {
        let orderDetailList = response.data;
        for(let i = 0; i < allocationDetails.value.length; i++){
          for(let j = 0; j < orderDetailList.length; j++){
            if(allocationDetails.value[i].rawProductBatch === orderDetailList[j].rawProductBatch){
              allocationDetails.value[i].remainWeight = orderDetailList[j].quantity - orderDetailList[j].allocationQuantity;
              allocationDetails.value[i].maxWeight = allocationDetails.value[i].remainWeight + allocationDetails.value[i].weight;
            }
          }
        }
      })
      loading.value = false;
    })
  }
  else{
    loading.value = true;
    getOrderDetail(orderNo.value).then(response => {
      orderDetails.value = response.data;
      allocationDetails.value = orderDetails.value.map((item, index) => {
        return {
          allocationDetailNo:planInfo.value.allocationNo + '-' +
              String(index + 1).padStart(3, '0'),
          allocationNo: planInfo.value.allocationNo,
          orderNo: orderNo.value,
          rawProductBatch: item.rawProductBatch,
          rawProductName: item.rawProductName,
          remainWeight: item.quantity - item.allocationQuantity,
          maxWeight: item.quantity - item.allocationQuantity,
          weight: 0,
          weightUnit: '吨',
          transportQuantity: 0,
        }
      })
      loading.value = false;
    })
  }
}

/** 随机生成调拨编号 **/
function generateAllocationNumber() {
  // 定义字符集，可以根据需要调整
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let orderNumber = '';
  for (let i = 0; i < 8; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    orderNumber += chars[randomIndex];
  }
  return "AL" + orderNumber;
}

/** 获取当前时间 **/
function getFormattedTime(){
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

function handleOrderGenerate(){
  if(planInfo.value.warehouseNo === ''){
    proxy.$modal.msgError("请选择仓库");
    return;
  }
  if(planInfo.value.allocationDate ===  '' || planInfo.value.allocationDate === null){
    proxy.$modal.msgError("请选择调拨日期");
    return;
  }
  if(planInfo.value.origin === ''){
    proxy.$modal.msgError("请输入发货地址");
    return;
  }
  if(planInfo.value.expectedDeliveryTime === '' || planInfo.value.expectedDeliveryTime === null){
    proxy.$modal.msgError("请输入预期到货时间");
    return;
  }
  if(allocationNo.value !== ''){
    handlePlanInfo();
    updateAllocationPlan(planInfo.value).then(response => {
      addAllocationDetailList(allocationDetails.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
      })
    })
    handleBack()
    return;
  }
  handlePlanInfo();
  addAllocationPlan(planInfo.value).then(response => {
    addAllocationDetailList(allocationDetails.value).then(response => {
      proxy.$modal.msgSuccess("新增成功");
    })
  })
  handleBack()
}

/** 退出 **/
function handleBack(){
  proxy.$tab.closeOpenPage(router.currentRoute.value);
  proxy.$router.push({
    path:'/AllocationPlan',
    query:{
      orderNo: orderNo.value
    }
  });
}

/** 调拨计划提交时数据整理 */
function handlePlanInfo(){
  planInfo.value.destination = warehouses.value.find(
      item => item.value === planInfo.value.warehouseNo).address;
  planInfo.value.weight = allocationDetails.value.reduce((acc, cur) => {return acc + cur.weight;}, 0);
  planInfo.value.weightUnit = allocationDetails.value[0].weightUnit;
  planInfo.value.transportQuantity = allocationDetails.value.reduce((acc, cur) => {return acc + cur.transportQuantity;}, 0);
}

initial()
</script>

<style scoped lang="scss">
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
</style>